﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinLibrary.FormMDI;
using WinLibrary.Controls;
using Test_Operator_Platform.Properties;
using EqInstruments;
using System.Threading.Tasks;
using WinLibrary.Messages;
using FKDatabase;
using System.IO;
using FigKey_TestExec_SL.Entity;
using System.Configuration;
using WinLibrary.FileOperate;
using FigKey_TestExec_SL.Reports;
using FigKey_TestExec_SL.Common;
using FigKey_TestExec_SL.Test;
using System.Diagnostics;
using Test_Operator_Platform.Model;

namespace Test_Operator_Platform.UI
{
    public partial class MainForm : Form
    {
        string user;
        bool admin;
        TestOperatorPlatform frmAutoTest;
        FrmManualTest frmManualTest;
        RunMode runMode;
        SNLabelEntity snEntity;
        Device device;
        TestPlanWork tpwork;
        bool statusBar = false;

        #region modbus 
        ViInstruments instrument;
        bool modbusOpenStatus = false;
        string modbusCOM = "COM3";
        string modbusCommand = "00 00 00 00 00 00 00 00";
        int modbusSleep = 30;
        int lmsStateTimeout = 1000;
        bool closeModbus = false;
        string lmsModbusFile = "";//保存Modbus状态文件
        string lmsChangeStateFile = "";//LMS换型状态文件
        string lmsPartnumberFile = "";//LMS同步型号列表文件
        #endregion

        enum RunMode
        {
            AutoTest,
            ManualTest
        }

        /// <summary>
        /// 防止界面缩放时出现卡顿或黑屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }

        public MainForm(string user, bool admin)
        {
            InitializeComponent();
            this.user = user;
            this.admin = admin;
            this.lbxTester.Text = this.user;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
	ExpressionCal.RegisterZExpress();
            this.snEntity = ConfigManage.ReadSNLabel();
            this.instrument = new ViInstruments();
            this.tpwork = new TestPlanWork();

            if (!this.admin)//屏蔽非管理员权限
            {
                this.tool_clearPinCount.Enabled = false;
                this.tool_reset.Enabled = false;
            }
            var bcs = System.Environment.CurrentDirectory + "\\image\\bcs.png";
            if (System.IO.File.Exists(bcs))
            {
                this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                this.pictureBox1.Image = Image.FromFile(bcs);
            }

            this.tool_statusbar.Image = Resources.勾选16;
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;

            OpenAutoTest();
            UpdateUITask();

            #region EventHandlers
            this.tool_autoTest.Click += Tool_autoTest_Click;
            this.tool_manualTest.Click += Tool_manualTest_Click;
            this.tool_LoadTestplan.Click += Tool_LoadTestplan_Click;
            this.tool_TestData.Click += Tool_TestData_Click;
            this.tool_testLog.Click += Tool_testLog_Click;
            this.tool_testFaultCode.Click += Tool_testFaultCode_Click;
            this.tool_reportSummary.Click += Tool_reportSummary_Click;
            this.tool_reportExport.Click += Tool_reportExport_Click;
            this.tool_statusbar.Click += Tool_statusbar_Click;
            this.tool_abort.Click += Tool_abort_Click;
            this.tool_help1.Click += Tool_help1_Click;
            this.tool_clearCount.Click += Tool_clearCount_Click;
            this.tool_clearPinCount.Click += Tool_clearPinCount_Click;
            this.tool_reset.Click += Tool_reset_Click;

            this.timer1.Tick += Timer1_Tick;
            this.SizeChanged += MainForm_SizeChanged;
            this.frmAutoTest.NotificationHandlers += FrmTestOperator_NotificationHandlers;
            this.FormClosed += MainForm_FormClosed;
            #endregion
        }

        private void Tool_testFaultCode_Click(object sender, EventArgs e)
        {
            FrmFaultManager frmFault = new FrmFaultManager();
            frmFault.ShowDialog();
        }

        private void Tool_testLog_Click(object sender, EventArgs e)
        {
            FrmTestHistory frmData = new FrmTestHistory(this.snEntity);
            frmData.ShowDialog();
        }

        private void Tool_reset_Click(object sender, EventArgs e)
        {
            string mResult;
            instrument.InstrumentMulCltQuery(modbusCOM, 1, "02 0f 00 00 00 10 02 00 00", 1, 250, 1, out mResult);
            LogHelper.Log.Info("重置Modbus:" + mResult);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.closeModbus = true;
            this.frmAutoTest.CloseForm = true;
            if (this.instrument != null)
            {
                this.instrument.InstrumentMulCltClose(this.modbusCOM);
            }
            System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
        }

        private void Tool_clearPinCount_Click(object sender, EventArgs e)
        {
            this.frmAutoTest.ClearPinCount();
        }

        private void Tool_clearCount_Click(object sender, EventArgs e)
        {
            this.frmAutoTest.ClearTestCount();
        }

        private void Tool_help1_Click(object sender, EventArgs e)
        {
            
        }

        private void Tool_abort_Click(object sender, EventArgs e)
        {
            Helper help = new Helper();
            help.ShowDialog();
        }

        private void Tool_statusbar_Click(object sender, EventArgs e)
        {
            if (!this.statusBar)
            {
                this.tool_statusbar.Image = null;
                this.statusBar = true;
                this.statusStrip1.Visible = false;
            }
            else
            {
                this.tool_statusbar.Image = Resources.勾选16;
                this.statusBar = false;
                this.statusStrip1.Visible = true;
            }
        }

        private void Tool_reportExport_Click(object sender, EventArgs e)
        {
            
        }

        private void Tool_reportSummary_Click(object sender, EventArgs e)
        {
            if (this.frmAutoTest == null)
                return;
            this.frmAutoTest.OpenReport();
        }

        private void Tool_TestData_Click(object sender, EventArgs e)
        {
           
        }

        private void FrmTestOperator_NotificationHandlers(bool status, bool modeUpdate, string message)
        {
            if (status)
            {
                this.tool_runStop.Enabled = true;
                this.tool_run.Enabled = true;
                this.tool_stop.Enabled = false;
            }
            if (modeUpdate)
            {
                if (this.tool_autoTest.Image == null)
                {
                    this.device.IsAutoMode = false;
                }
                else
                {
                    this.device.IsAutoMode = true;
                }
            }
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            this.lbxdateNow.Text = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            
        }

        private void Tool_LoadTestplan_Click(object sender, EventArgs e)
        {
            if (this.frmAutoTest == null)
                return;
            this.frmAutoTest.ReadTestPlan();
        }

        private void Tool_manualTest_Click(object sender, EventArgs e)
        {
            OpenManualTest();
        }

        private void Tool_autoTest_Click(object sender, EventArgs e)
        {
            OpenAutoTest();
        }

        private void OpenAutoTest()
        {
            this.device = new Device() { ModbusPort = this.modbusCOM, Instrument = this.instrument };
            if (this.frmAutoTest == null)
                this.frmAutoTest = new TestOperatorPlatform(this.user, this.snEntity, this.tpwork, ref this.device);
            this.runMode = RunMode.AutoTest;
            this.tool_autoTest.Image = Resources.勾选16;
            this.tool_manualTest.Image = null;
            this.tool_TestData.Enabled = true;
            this.tool_file.Enabled = true;
            this.tool_report.Enabled = true;
            this.frmAutoTest.device.IsAutoMode = true;
            //保存配置

            FrmMDI.PanelAddForm(this.plContainer, this.frmAutoTest);
        }

        private void OpenManualTest()
        {
            if (this.frmManualTest == null)
                this.frmManualTest = new FrmManualTest();
            this.runMode = RunMode.ManualTest;
            this.tool_runStop.Enabled = false;
            this.tool_autoTest.Image = null;
            this.tool_manualTest.Image = Resources.勾选16;
            this.frmAutoTest.device.IsAutoMode = false;
            //保存配置

            //FrmMDI.PanelAddForm(this.plContainer, this.frmManualTest);
        }

        private void UpdateUITask()
        {
            Task.Factory.StartNew(()=>
            {
                while (true)
                {
                    //this.tpwork.UpdateTestUI();//更新测试数据
                    GridViewHelper.StartBackgroundTask();
                    System.Threading.Thread.Sleep(1);
                }
            });
        }
    }
}
